package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime over = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", start);
            map.put("end", over);
            map.put("status", Orders.COMPLETED);
            Double count = orderMapper.turnoverStatistics(map);
            count = count == null ? 0.0 : count;
            turnoverList.add(count);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime over = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", start);
            map.put("end", over);
            Integer cntTotal = userMapper.totalUserList(map);
            cntTotal = cntTotal == null ? 0 : cntTotal;
            totalUserList.add(cntTotal);
        }
        newUserList.add(0);
        for (int i = 1; i < totalUserList.size(); i++) {
            newUserList.add(totalUserList.get(i) - totalUserList.get(i - 1));
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime over = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", start);
            map.put("end", over);
            Integer cntTotal = orderMapper.orderCountList(map);
            cntTotal = cntTotal == null ? 0 : cntTotal;
            orderCountList.add(cntTotal);
            map.put("status", Orders.COMPLETED);
            Integer cntTotal2 = orderMapper.validOrderCountList(map);
            cntTotal2 = cntTotal2 == null ? 0 : cntTotal2;
            validOrderCountList.add(cntTotal2);
        }

        LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime over = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", start);
        map.put("end", over);
        Integer orderCount = orderMapper.orderCountList(map);
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.validOrderCountList(map);
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate((double) validOrderCount / orderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime over = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", start);
        map.put("end", over);
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> list = orderDetailMapper.top10(map);
        for (GoodsSalesDTO goodsSalesDTO : list) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDate, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间: " + begin + "至" + end);

            XSSFRow row4 = sheet1.getRow(3);
            row4.getCell(2).setCellValue(businessData.getTurnover());
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row5 = sheet1.getRow(4);
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            row5.getCell(4).setCellValue(businessData.getUnitPrice());

            int beginRow = 7;
            while (!beginDate.equals(endDate)) {
                LocalDateTime tempBegin = LocalDateTime.of(beginDate, LocalTime.MIN);
                LocalDateTime tempEnd = LocalDateTime.of(beginDate, LocalTime.MAX);
                XSSFRow row = sheet1.getRow(beginRow);
                BusinessDataVO temp = workspaceService.getBusinessData(tempBegin, tempEnd);

                row.getCell(1).setCellValue(beginDate.toString());
                row.getCell(2).setCellValue(temp.getTurnover());
                row.getCell(3).setCellValue(temp.getValidOrderCount());
                row.getCell(4).setCellValue(temp.getOrderCompletionRate());
                row.getCell(5).setCellValue(temp.getUnitPrice());
                row.getCell(6).setCellValue(temp.getNewUsers());

                beginDate = beginDate.plusDays(1);
                beginRow++;
            }
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
